package com.it.you.common.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class EasyLogAspect {


    /**
     * 通过@Pointcut指定切入点 ，这里指定的切入点为EasyLog注解类型，也就是
     * 被@EasyLog注解修饰的方法，进入该切入点
     */
    @Pointcut(value = "@annotation(com.it.you.common.aop.EasyLog)")
    private void pointcut() {

    }

    /**
     * 在方法执行前后
     *
     * @param point
     * @param easyLog
     * @return
     * @throws Throwable
     */
    @Around(value = "pointcut() && @annotation(easyLog)")
    public Object around(ProceedingJoinPoint point, EasyLog easyLog) throws Throwable {
        Object[] args = point.getArgs();
        //拦截的类名
        Class clazz = point.getTarget().getClass();
        //拦截的方法
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        String methodName = methodSignature.getMethod().getName();
        String[] parameterNames = methodSignature.getParameterNames();
        Class[] parameterTypes = methodSignature.getParameterTypes();

        StringBuilder sb = new StringBuilder();
        sb.append("ClassName: ").append(clazz.getName()).append("\n");
        sb.append("MethodName    : ").append(methodName).append("\n");
        sb.append("ParamNames    : ").append(JSON.toJSONString(parameterNames)).append("\n");
        sb.append("ParamTypes    : ").append(JSON.toJSONString(parameterTypes)).append("\n");
        sb.append("ParamValues    : ").append(JSON.toJSONString(args)).append("\n");
        log.info(sb.toString());
        //执行程序
        Object object = point.proceed();
        return object;
    }

}
